// var configBaseUrl = "192.168.0.111";
var configBaseUrl = "119.61.37.98";
window.config = {
	url:"http://"+configBaseUrl+"/webserver",
	host:"http://"+configBaseUrl,
    parseUrl:"http://"+configBaseUrl+":8088/parse",
	project:"webapp",
    synHost: "http://192.168.0.190:8000/",
    jdUrl: "http://119.61.37.98:800"
    // jdUrl: "http://106.3.200.10:800"
    // jdUrl: "http://192.168.0.226:800"
}
var userLoginToken; //用户登录token

//判断是否月度数据，线下月和线上月都属于月度数据
function isMonthType() {
    if (window.parent.workMode == "month" || window.parent.workMode == "online_m"|| window.parent.workMode == "PDK_M") {
        return true;
    }
    return false;
}
//判断是否线下模式
function isOfflineType() {
    if (window.parent.workMode == "month" || window.parent.workMode == "week") {
        return true;
    }
    return false;
}

function addTab(title,href,icon){
	var tt = $("#tabs");
	if(tt.tabs("exists",title)){
		tt.tabs('select',title);
		refreshTab({tabTitle:title,url:href});
	}else{
		if(href){
			var content = "<iframe scrolling='auto' frameborder='0' src=\'"+href+
			"\' style='width:100%;height:100%;display:block;'></iframe>"
		}else{
			var content = "未实现";
		}
		tt.tabs('add',{
			title:title,
			closable:true,
			content:content,
			iconCls:icon|'icon-default'
		});

	}
}
function refreshTab(cfg){
	var refresh_tab = cfg.tabTitle?$("#tabs").tabs('getTab',cfg.tabTitle):$("#tabs").tabs('getSelected');
	if(refresh_tab && refresh_tab.find("iframe").length > 0){
		var _refresh_iframe = refresh_tab.find("iframe")[0];
		var refresh_url  = cfg.url?cfg.url:_refresh_tab.src;
		_refresh_iframe.contentWindow.location.href=refresh_url;
	}
}
function closeCurrentTab(flag){
    var tab = $("#tabs").tabs("getSelected");
    var index = $("#tabs").tabs('getTabIndex',tab);
    if(index>0){
        $("#tabs").tabs("close",index);
        if(flag){
            var tab2 = $("#tabs").tabs("getSelected");
            var index2 = $("#tabs").tabs("getTabIndex",tab2);
            tab2[0].firstChild.contentWindow.searchBy();
        }
    }
}
//页面带参跳转，获取参数的方法
function getQueryParameter(paramName){
    var re = new RegExp(paramName+"=([^\&]*)","i");//RegExp 对象表示正则表达式，它是对字符串执行模式匹配的强大工具。
    var search = document.location.search;//获取参数
    if(search){
        var res = re.exec(search);
        if(res==null){
            return null;
        }
        return res[1];
    }
    return null;
}

function getFormData(form){
	var data = {};
	var params = $(form).serialize();
	params = decodeURI(params);//解决中文编码问题
    params = params.replace(/\+/g," ");
    params = params.replace(/%2B/g,"+");
    params = params.replace(/%2F/g,"/");
    params = params.replace(/%3F/g,"?");
    params = params.replace(/%3A/g,":");
    params = params.replace(/%40/g,"@");
    params = params.replace(/%21/g,"!");
    params = params.replace(/%23/g,"#");
    params = params.replace(/%25/g,"%");
    params = params.replace(/%26/g,"&");
    params = params.replace(/%3B/g,";");
    params = params.replace(/%2C/g,",");
	var keyvalues = params && params.split("&");
	$(keyvalues).each(function(i,item){
		var key = item.split("=")[0];
		var value = item.split("=")[1];
		if(Object.prototype.hasOwnProperty.call(data,key)){
            var isArray = Array.isArray(data[key]);
            if(isArray){
            	data[key].push(value);
            }else{
            	var tmp = data[key];
				data[key] = [];
				data[key].push(tmp);
				data[key].push(value);
            }
		}else{
			data[key] = value;
		}
	});
	return data;
}

function statusFormatter(val,row){
    if(val=="DISABLE"){
        return "<a class='l-btn-left l-btn-icon-left' style='width:24px;height:24px;'><span class='l-btn-icon icon-no'></span></a>";
    }else{
        return "<a class='l-btn-left l-btn-icon-left' style='width:24px;height:24px;'><span class='l-btn-icon icon-ok'></span></a>";
    }
}
function disabledTypeFormatter(val,row) {
    var res="";
    switch (val) {
        case "OBLITERATE":
            res="退货核销";
            break;
        case "SALESCOUNT":
            res="销量异常";
            break;
        case "SALESPRICE":
            res="销价异常";
            break;
        default:
            break;
    }
    return res;
}
function patternFormatter(val,row) {
    var res="";
    switch (val) {
        case "PART":
            res="yyyy年M月d日";
            break;
        case "PART10":
            res="yyyy年MM月dd日";
            break;
        case "PART1":
            res="yyyy-M-d";
            break;
        case "PART2":
            res="yyyy/M/d";
            break;
        case "PART3":
            res="yyyy.M.d";
            break;
        case "PART9":
            res="yyyy.MM.dd";
            break;
        case "PART4":
            res="yyyy-M-d HH:mm:ss";
            break;
        case "PART5":
            res="yyyy/M/d HH:mm";
            break;
        case "PART6":
            res="yyyyMMdd";
            break;
        case "PART7":
            res="MM.dd";
            break;
        case "PART8":
            res="M-d";
            break;
        default:
            break;
    }
    return res;
}

function initBrandSelect(selectId, onchange, callback){
	var dtd = $.Deferred();
	$.ajax({
        url:config.url +"/brand/getAll",
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                data.unshift({"name":"","code":""});
                $("#"+selectId).combobox({
                    "textField":"name",
                    "valueField":"code",
                    "panelHeight":150,
                    "prompt":"--请选择--",
                    "data":data,
                    onChange:function(newValue,oldValue){
                    	if(onchange && typeof onchange === 'function'){
                    		onchange.call(this,newValue);
                    	}
                    }
                });
                callback && typeof(callback)==='function' && callback();
            }
            dtd.resolve();
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
        	dtd.resolve();
        }
    })
    return dtd.promise();
}

function initBrandSelectC(selectId, onchange, callback,categoryCode,brandcode){
    var dtd = $.Deferred();
    $.ajax({
        url:config.url +"/brand/getCategoryCodeAll?categoryCode="+categoryCode,
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                data.unshift({"name":"","code":""});
                $("#"+selectId).combobox({
                    "textField":"name",
                    "valueField":"code",
                    "panelHeight":150,
                    "prompt":"--请选择--",
                    "data":data,
                    onChange:function(newValue,oldValue){
                        if(onchange && typeof onchange === 'function'){
                            onchange.call(this,newValue);
                        }
                    },
                    onLoadSuccess: function () { //数据加载完毕事件
                        if(brandcode){
                            // var pattern = /\d{6}/;
                            // if(!pattern.test(str)){
                            $("#"+selectId).combobox('select', brandcode);
                            // }

                        }

                    }
                });
                callback && typeof(callback)==='function' && callback();
            }
            dtd.resolve();
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
            dtd.resolve();
        }
    })
    return dtd.promise();
}
function initBrandallSelect(selectId, onchange, callback){
	var dtd = $.Deferred();
	$.ajax({
        url:config.url +"/brand/getAll",
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                data.unshift({"name":"all","code":"all"});
                $("#"+selectId).combobox({
                    "textField":"name",
                    "valueField":"code",
                    "panelHeight":150,
                    "prompt":"all",
                    "data":data,
                    onChange:function(newValue,oldValue){
                    	if(onchange && typeof onchange === 'function'){
                    		onchange.call(this,newValue);
                    	}
                    }
                });
                callback && typeof(callback)==='function' && callback();
            }
            dtd.resolve();
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
        	dtd.resolve();
        }
    })
    return dtd.promise();
}

function initCategorySelect(selectId, onchange, callback){
	var dtd = $.Deferred();
	$.ajax({
        url:config.url +"/category/getAll",
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                // data.unshift({"name":"-请选择-","code":""});
                $("#"+selectId).combobox({
                    "textField":"name",
                    "valueField":"code",
                    "panelHeight":150,
                    "data":data,
                    onChange:function(newValue,oldValue){
                        var val = $(this).combobox("getText");
                        var textField = $(this).combobox("options").textField;
                        var matchSize = $(this).combobox("getData").filter(function(item){
                            return item[textField]==val;
                        }).length;
                        if(matchSize!=1){
                            return false;
                        }
                        if(newValue=="")return false;
                    	if(onchange && typeof onchange === 'function'){
                    		onchange.call(this,newValue);
                    	}
                    }
                });
                callback && typeof(callback)==='function' && callback();
            }
            dtd.resolve();
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
        	dtd.resolve();
        }
    })
    return dtd.promise();
}
//新加方法用于无品类权限时 支持查询全部
function initCategorySelectnew(selectId, onchange, callback){
	var dtd = $.Deferred();
	$.ajax({
        url:config.url +"/category/getAll",
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                data.unshift({"name":"","code":""});
                $("#"+selectId).combobox({
                    "textField":"name",
                    "valueField":"code",
                    "panelHeight":150,
                    "prompt": "--请选择--",
                    "data":data,
                    onChange:function(newValue,oldValue){
                        var val = $(this).combobox("getText");
                        var textField = $(this).combobox("options").textField;
                        var matchSize = $(this).combobox("getData").filter(function(item){
                            return item[textField]==val;
                        }).length;
                        if(matchSize!=1){
                            return false;
                        }
                        if(newValue=="")return false;
                    	if(onchange && typeof onchange === 'function'){
                    		onchange.call(this,newValue);
                    	}
                    }
                });
                callback && typeof(callback)==='function' && callback();
            }
            dtd.resolve();
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
        	dtd.resolve();
        }
    })
    return dtd.promise();
}

function initUserCategorySelect(selectId, onchange, callback){
    var dtd = $.Deferred();
    var data = window.parent.userCategoryManageList;
    if(data){
        // data.unshift({"text":"-请选择-","code":""});
        $("#"+selectId).combobox({
            "textField":"name",
            "valueField":"code",
            "panelHeight":150,
            "data":data,
            onChange:function(newValue,oldValue){
                if(onchange && typeof onchange === 'function'){
                    var val = $(this).combobox("getText");
                    var textField = $(this).combobox("options").textField;
                    var matchSize = $(this).combobox("getData").filter(function(item){
                        return item[textField]==val;
                    }).length;
                    if(matchSize!=1){
                        return false;
                    }
                    if(newValue=="")return false;
                    onchange.call(this,newValue);
                }
            }
        }).combobox("setValue",data[0]);
        callback && typeof(callback)==='function' && callback();
    }
    dtd.resolve();
    return dtd.promise();
}

function initProvinceSelect(selectId, onchange){
    var dtd = $.Deferred();
	$.ajax({
        url:config.url +"/dictionary/getDictionaryByType?type=LOCATION_PROVINCE",
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                data.unshift({"name":"-请选择-","code":""});
                $("#"+selectId).combobox({
                    "textField":"name",
                    "valueField":"code",
                    panelHeight:150,
                    "data":data,
                    onChange:function(newValue,oldValue){
                    	onchange && typeof(onchange)==='function' && onchange.call(this,newValue);
                    }
                });
                dtd.resolve();
            }
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
            dtd.reject();
        }
    });
	return dtd.promise();
}


function initFullCitySelect(selectId){
	$.ajax({
        url:config.url+'/city/getAll',
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                data.unshift({"name":"-请选择-","code":null});
                $("#"+selectId).combobox({
                    "textField":"name",
                    "valueField":"code",
                    "panelHeight":150,
                    "data":data
                });
            }
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
        }
    })
}


function initCitySelect(selectId, provinceCode){
	$.ajax({
        url:config.url+'/dictionary/getCityByProvince/'+provinceCode,
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                data.unshift({"name":"-请选择-","code":null});
                $("#"+selectId).combobox({
                    "textField":"name",
                    "valueField":"code",
                    "panelHeight":150,
                    "data":data
                });
            }
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
        }
    })
}

function initCitySelect(selectId, selectId2, provinceCode){
	$.ajax({
        url:config.url+'/dictionary/getCityByProvince/'+provinceCode,
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                data.unshift({"name":"-请选择-","code":""});
                $("#"+selectId).combobox({
                    "textField":"name",
                    "valueField":"code",
                    "data":data
                });
                $("#"+selectId2).combobox({
                    "textFiled":"text",
                    "valueField":"code",
                    "data":data
                });
            }
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
        }
    })
}

function initChannelSelect(channelSelectId, mallSelectId, initCallback,mallSelectId2){
    var dtd = $.Deferred();
	$.ajax({
        url:config.url +"/channel/getAll",
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                data.unshift({"name":"","code":"","selected":true});
                $("#"+channelSelectId).combobox({
                    "textField":"name",
                    "valueField":"code",
                    "panelHeight":"150",
                    "prompt":"--请选择--",
                    "data":data,
                    "onSelect": function(rec){
                    	if(!!rec.code && mallSelectId && $("#"+mallSelectId)){
                    		// 初始化“商场”下拉框
                    		initMallSelect(mallSelectId, rec.code,mallSelectId2);
                    	}
                    }
                });
                dtd.resolve();
                // 回调函数
                if(typeof initCallback === "function"){
                	if(data.length>=2){
                		$("#"+channelSelectId).combobox('select', data[1]['code']);
                	}
                	initCallback();
                }
            }
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
            dtd.reject();
        }
    });
	return dtd.promise();
}

function initMallSelect(selectId, channelCode,mallSelectId2){
	$.ajax({
        url:config.url +"/mall/getByChannelCode?channelCode="+channelCode,
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                data.unshift({"name":"","code":"","selected":true});
                $("#"+selectId).combobox({
                    "textField":"name",
                    "valueField":"code",
                    "panelHeight":150,
                    "prompt":"--请选择--",
                    "data":data
                });
                if (mallSelectId2) {
                    $("#"+mallSelectId2).combobox({
                        "textField":"name",
                        "valueField":"code",
                        "panelHeight":150,
                        "prompt":"--请选择--",
                        "data":data
                    });
                }
            }
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
        }
    })
}

function initWeekSelect(selectId, onchange){
    var dtd = $.Deferred();
    //统一改为53周，在选择年的时候，week没有变，但是有的year标签是select，有的是year，无法统一
    var arr = [];
    for(var i=1; i<=53; i++){
        arr.push(getOption(i,"第"+i+"周"));
    }
    $("#"+selectId).combobox({
        "valueField":"code",
        "panelHeight":"150",
        "data":arr,
        onChange:function(newValue,oldValue){
            onchange && typeof(onchange)==='function' && onchange.call(this,newValue);
        }
    });
    $("#"+selectId).combobox('select', window.parent.timeData.weekInYear);
    // $.ajax({
    //     url:config.url +"/weekConfig/getWeeksInYear",
    //     data:{"year":window.parent.timeData.year},
    //     type:"get",
    //     xhrFields:{withCredentials:true},
    //     success:function (data) {
    //     	if(data){
    //     		var arr = [];
    //         	for(var i=1; i<=data; i++){
    //         		arr.push(getOption(i,"第"+i+"周"));
    //         	}
    //         	$("#"+selectId).combobox({
    //                 "valueField":"code",
    //                 "panelHeight":"150",
    //                 "data":arr,
    //                 onChange:function(newValue,oldValue){
    //                 	onchange && typeof(onchange)==='function' && onchange.call(this,newValue);
    //                 }
    //             });
    //         	//TODO 设置当前周期周
    //         	$("#"+selectId).combobox('select', window.parent.timeData.weekInYear);
    //         	dtd.resolve();
    //         }
    //     },
    //     error:function(XMLHttpRequest,textStatus,errorThrown){
    //         dtd.reject();
    //     }
    // });
	return dtd.promise();
}
function initModelSpecSelect(settingmodelwrapper,categoryCode,cmp) {
    var dtd = $.Deferred();
    var dd = [];
    $.ajax({
        url:config.url+"/categoryMetadata/getMainMetadata/"+categoryCode,
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                dd = data.map(function (item) {
                    var content = renderComponent(item);
                    return content;
                });
                if(cmp){
                   cmp1 = data[0];
                }
                $("#"+settingmodelwrapper).html(dd.join(""));
                $.parser.parse($("#"+settingmodelwrapper));
                dtd.resolve();
            }
        },
        error:function (XMLHttpRequest,textStatus,errorThrown) {
            dtd.reject();
        }
    });
    return dtd.promise();
}

function initModelSearchSelect(propCode,metadatawrapper,categoryCode,propValue){
    var dtd = $.Deferred();
    var dd = [];
    $.ajax({
        url:config.url+"/categoryMetadata/getNameByCategoryCode?categoryCode="+categoryCode,
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                var obj_map = {};
                data.unshift({"name":"全部","code":""});
                dd = data.map(function (item) {
                    obj_map[item.code] = item.values;
                });
                $("#"+propCode).combobox({
                    textField:"name",
                    valueField:"code",
                    prompt:"--请选择--",
                    panelHeight:"200px",
                    data:data,
                    onChange:function (newValue,oldValue) {
                        var sub_data = obj_map[newValue];
                        //根据是否有值来决定是下拉框还是文本框
                        var inner = "";
                        var proValueName = propValue || "propValue";
                        if(sub_data ){
                            inner = "<select class='easyui-combobox' name='"+proValueName+"' data-options=\"panelHeight:'auto'\" style='width:100px;' prompt='--请选择--'> <option></option>";
                            if( sub_data == ""){
                                inner += "<option value='true'>"+"是"+"</option>";
                                inner += "<option value='false'>"+"否"+"</option>";
                            }else{
                                for(var i=0;i<sub_data.length;i++){
                                        inner += "<option >"+sub_data[i]+"</option>";
                                }
                            }

                            inner += "</select>"
                        }else{
                            inner = "<input type='text' class='easyui-textbox' name='"+proValueName+"' style='width:100px' prompt='请输入值'/>"
                        }
                        $("#"+metadatawrapper).html(inner);
                        $.parser.parse($("#"+metadatawrapper));
                    }
                });
                dtd.resolve();
            }
        },
        error:function (XMLHttpRequest,textStatus,errorThrown) {
            dtd.reject();
        }
    });
    return dtd.promise();
}
function initModelSearchSelect1(propCode,metadatawrapper,categoryCode,propValue){
    var dtd = $.Deferred();
    var dd = [];
    $.ajax({
        url:config.url+"/categoryMetadata/getNameByCategoryCode?categoryCode="+categoryCode,
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                var obj_map = {};
                dd = data.map(function (item) {
                    obj_map[item.code] = item.values;
                });
                // data.unshift({"name":"规格状态","code":"propStatus"});
                data.unshift({"name":"上市价格","code":"onSellPrice"});
                data.unshift({"name":"上市年份","code":"onSellYear"});
                data.unshift({"name":"上市月份","code":"onSellMonth"});
                data.unshift({"name":"上市周","code":"onSellWeek"});
                // data.unshift({"name":"品牌","code":"brandCode"});
                data.unshift({"name":"-请选择-","code":""});
                $("#"+propCode).combobox({
                    textField:"name",
                    valueField:"code",
                    panelHeight:"200px",
                    data:data,
                    onChange:function (newValue,oldValue) {
                        if("propStatus"==newValue){
                            inner = "<select class='easyui-combobox' name='propValue1' data-options=\"panelHeight:'auto'\" style='width:200px;' prompt='--请选择--'> <option></option>";
                                    inner += "<option value=\"\">--请选择--</option>\n" +
                                        "                        <option value=\"CONFIRMALL\">全部确认</option>\n" +
                                        "                        <option value=\"CONFIRMONE\" >一级</option>\n" +
                                        "                        <option value=\"CONFIRMTWO\" >两级</option>\n" +
                                        "                        <option value=\"CONFIRMTHREE\">三级</option>\n" +
                                        "                        <option value=\"UNCOFIRMED\">未确认</option>\n" +
                                        "                        <option value=\"UNABLECOFIRED\">无法找到信息</option>\n" +
                                        "                        <option value=\"UNRELEASED\">暂未发布</option>";

                            inner += "</select>"
                        }else{
                            var sub_data = obj_map[newValue];
                            //根据是否有值来决定是下拉框还是文本框
                            var inner = "";
                            var proValueName = propValue || "propValue1";
                            if(sub_data ){
                                inner = "<select class='easyui-combobox' name='"+proValueName+"' data-options=\"panelHeight:'auto'\" style='width:200px;' prompt='--请选择--'> <option></option>";
                                if( sub_data == ""){
                                    inner += "<option value='true'>"+"是"+"</option>";
                                    inner += "<option value='false'>"+"否"+"</option>";
                                }else{
                                    for(var i=0;i<sub_data.length;i++){
                                        inner += "<option >"+sub_data[i]+"</option>";
                                    }
                                }

                                inner += "</select>"
                            }else{
                                inner = "<input type='text' class='easyui-textbox' name='"+proValueName+"' style='width:200px' prompt='请输入值'/>"
                            }
                        }

                        $("#"+metadatawrapper).html(inner);
                        $.parser.parse($("#"+metadatawrapper));
                    }
                });

                dtd.resolve();
            }
        },
        error:function (XMLHttpRequest,textStatus,errorThrown) {
            dtd.reject();
        }
    });
    return dtd.promise();
}
function getOption(code, text){
	return {"text":text,"code":code};
}

function initYearSelect(selectId, onchange){
	var data = [];
	//TODO 获取当前年
	var year = window.parent.timeData.year;
	var years = window.parent.years;
	$(years).each(function (index,item) {
        data.push(getOption(item,item+"年"));
    });
	$("#"+selectId).combobox({
        "valueField":"code",
        "panelHeight":"150",
        "data":data,
        onChange:function(newValue,oldValue){
        	onchange && typeof(onchange)==='function' && onchange.call(this,newValue);
        }
    });
	$("#"+selectId).combobox('select', year);
}

function initMonthSelect(selectId, onchange){
	var data = [];
	for(var i=1; i<=12; i++){
		data.push(getOption(i, i+"月"));
	}
	$("#"+selectId).combobox({
        "valueField":"code",
        "panelHeight":"150",
        "data":data,
        onChange:function(newValue,oldValue){
        	onchange && typeof(onchange)==='function' && onchange.call(this,newValue);
        }
    });
	//TODO 设置当前周期月
	$("#"+selectId).combobox('select', window.parent.timeData.monthInYear);
}
function initMonthWeek(monthId,weekId) {
	initYearSelect("year");
    if(isMonthType()){
    	//隐藏周
        if (weekId){
            $("#"+weekId).remove();
            return initMonthSelect("month");
        }
    }else {
        //隐藏月
        if(monthId){
            $("#"+monthId).remove();
            return initWeekSelect("week");
        }
    }
    return $.Deferred().resolve();
}
function boolFormatter(val,row){
	if(val==false){
        return "否";
	}else if(val==true){
		return "是";
	}else {
        return "--";
    }
}
function typeFormatter(type){
   var res = "";
   switch(type){
     case "SUPERMARKET":
        res = "超市";
        break;
     case "DEPARTMENT_STORE":
        res="百货";
        break;
     case "PRO_SHOP":
        res="家电";
        break;
       case "KA":
           res="KA";
           break;
       case "BUILDING_MATERIAL":
           res="建材";
           break;
       case "SPECIALTY_EB":
           res="专业电商";
           break;
       case "PLATFORM_EB":
           res="平台电商";
           break;
     default:
        res="超市";
   }
   return res;
}
function marketLevelFormatter(val){
	var res = "";
	switch(val){
		case "1":
			res = "";
			break;
		default:
			res = "";
	}
	return res;
}
function cityLevelFormatter(val){
	var res = "";
	switch(val){
		case "":
			res = "";
			break;
		default:
			res = "";
	}
	return res;
}
function cityScaleFormatter(val){
	var res = "";
	switch(val){
		case "":
			res = "";
			break;
		default:
			res = "";
	}
	return res;
}
function reportStatusFormatter(val,row) {
    var res = "";
    switch(val){
        case "WAITING":
            res = "未上报";
            break;
        case "CHANNEL":
            res = "渠道审核";
            break;
        case "PRODUCT":
            res = "产品审核";
            break;
        default:
            res = "";
    }
    return res;
}
function middleBrandFormatter(val,row){
    if(row.middleBrand&&row.middleBrand.length>0){
        row.middleBrand.join(",");
    }
    return "";
}
function middleModelFormatter(val,row){
    if(row.middleModel&&row.middleModel.length>0){
        row.middleModel.join(",");
    }
    return "";
}

function middleCategoryFormatter(val,row){
    if(row.middleCategory&&row.middleCategory.length>0){
        row.middleCategory.join(",");
    }
    return "";
}
function northFormatter(val){
	var res = "";
	switch(val){
		case "":
			res = "";
			break;
		default:
			res = "";
	}
	return res;
}
function areaFormatter(val){
	var res = "";
	switch(val){
		case "":
			res = "";
			break;
		default:
			res = "";
	}
	return res;
}
function btnFormatter(val,row){

}
function reportTypeFormatter(val,row) {
    var res = "";
    switch(val){
        case "WEEK":
            res = "周报";
            break;
        case "MONTH":
            res = "月报";
            break;
        case "ONLINE":
            res = "电商周";
            break;
        case "ONLINE_M":
            res = "线上月";
            break;
        case "PDK_W":
            res = "拼抖快周";
            break;
        case "PDK_M":
            res = "拼抖快月";
            break;
        default:
            res="月报";
    }
    return res;
}
function analyzeModeFormatter(val,row) {
    var res = "";
    switch(val){
        case "HISTORY":
            res = "历史数据代换";
            break;
        case "MANUAL":
            res="人工代换";
            break;
        case "OBLITERATE":
            res="退货核销";
            break;
        default:
            res="系统代换";
    }
    return res;
}

function timeFormatter(val,row){
    if(!val) return "--";
    return dateFormat(val,"yyyy-MM-dd hh:mm:ss");
}

function dateFormat(time,format) {
    var date = new Date(time);
    var map ={
        'M' : date.getMonth()+1,//month
        'd' : date.getDate(),//date
        'h' : date.getHours(),//hours
        'm' : date.getMinutes(),//minutes
        's' : date.getSeconds() //seconds
    };
    format = format.replace(/([yMdhms])+/g,function(all,t){
        var v = map[t];
        if(v!=undefined){
            if(all.length>1){
                v = '0'+v;
                v = v.substr(v.length-2);
            }
            return v;
        }else if(t=='y'){
            return (date.getFullYear()+'').substr(4-all.length);
        }
        return all;
    });
    return format;
}

function changeProperty2String(obj){
	for(var key in obj){
		var tmp = obj[key];
		var type = typeof tmp;
		if("boolean"==type){
			obj[key] = tmp.toString();
		}
	}
	return obj;
}

function channelFormatter(val,row,index) {
    return row.channelName;
}

function transfer(data){
	var result = {};
	for(i in data){
		var tmp = data[i];
		if(tmp){
			result[i] = tmp;
		}
	}
	return result;
}
function load(){
	$("<div class='datagrid-mask'></div>").css({
	  display:'block',
	  width:'100%',
	  height:$(window).height(),
	  zIndex:100
	}).appendTo("body");
	$("<div class='datagrid-mask-msg'></div>").html("正在保存，请稍后...").css({
	  display:'block',
	  left:($(document.body).outerWidth(true)-190)/2,
	  top:($(window).height()-45)/2
	}).appendTo("body");

}
function disLoad(){
	$(".datagrid-mask").remove();
	$(".datagrid-mask-msg").remove();
}

function setNav(){
	var nav = "当前位置：<a class='nav-item'>{{rootMenu}}</a>&gt&gt<a class='nav-item'>{{secondMenu}}</a>";
    var rootMenu = window.parent.window.getRootMenu();
    var secondMenu = window.parent.window.getSecondMenu();
    nav = nav.replace("{{rootMenu}}",rootMenu);
    nav = nav.replace("{{secondMenu}}",secondMenu);
	document.getElementById("nav").innerHTML = nav;
}

/**
 * 深拷贝
 * @param object
 */
function deepClone(object) {
    var tmp = JSON.stringify(object);
    return JSON.parse(tmp);
}
e = "dslkfjvhlksdghfSDIHFOIE";
function getModuleName() {
    var url = window.location.href;
    var reg = new RegExp(/.*(\/\w+)\/([^.]+).*/g);
    var module = window.location.href.replace(reg,"$1");
    return module;
}
function logout() {
    $.ajax({
        url:config.url + "/user/logout",
        type:"get",
        xhrFields:{withCredentials:true},
        success:function(data){
            console.log(data);
            location.href = "/webapp/";
        },
        error:function(data){
            console.log(data);
        }
    });
}
function transfer2url(data) {
    var res = [];
    for(var i in data){
        if(data[i]){
            res.push(i+"="+data[i]);
        }
    }
    return res.join("&");
}
function initUserSelect(channelSelectId, initCallback){
    var dtd = $.Deferred();
    $.ajax({
        url:config.url +"/user/getByUsername",
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                data.unshift({"name":"-请选择-","code":"","selected":true});
                $("#"+channelSelectId).combobox({
                    "textField":"name",
                    "valueField":"name",
                    "panelHeight":"150",
                    "data":data
                });
                dtd.resolve();
                // 回调函数
                if(typeof initCallback === "function"){
                    if(data.length>=2){
                        $("#"+channelSelectId).combobox('select', data[1]['code']);
                    }
                    initCallback();
                }
            }
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
            dtd.reject();
        }
    });
    return dtd.promise();
}

function initMetadataSelect(selectId,categoryCode, onchange, callback){
    var dtd = $.Deferred();
    $.ajax({
        url:config.url +"/categoryMetadata/getByFjmetadata?categoryCode="+categoryCode,
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                data.unshift({"name":"-请选择-","code":""});
                $("#"+selectId).combobox({
                    "textField":"name",
                    "valueField":"code",
                    "panelHeight":150,
                    "data":data,
                    onChange:function(newValue,oldValue){
                        var val = $(this).combobox("getText");
                        var textField = $(this).combobox("options").textField;
                        var matchSize = $(this).combobox("getData").filter(function(item){
                            return item[textField]==val;
                        }).length;
                        if(matchSize!=1){
                            return false;
                        }
                        if(newValue=="")return false;
                        if(onchange && typeof onchange === 'function'){
                            onchange.call(this,newValue);
                        }
                    }
                });
                callback && typeof(callback)==='function' && callback();
            }
            dtd.resolve();
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
            dtd.resolve();
        }
    })
    return dtd.promise();
}
/**
 * 查出所有开放的公司
 * @param selectId
 * @param onchange
 * @param callback
 * @returns {*}
 */
function initCompanyS(selectId, company, callback){
    var dtd = $.Deferred();
    $.ajax({
        url:config.url +"/recipientUser/getAllCompany",
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                data.unshift({"name":"","code":""});
                $("#"+selectId).combobox({
                    "textField":"name",
                    "valueField":"name",
                    "panelHeight":150,
                    "prompt":"--请选择--",
                    "data":data,
                    "onSelect": function(rec){
                        if(!!rec.code && company && $("#"+company)){
                            // 初始化“商场”下拉框
                            initPrincipalS(company, rec.name);
                        }
                    }
                });
                callback && typeof(callback)==='function' && callback();
            }
            dtd.resolve();
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
            dtd.resolve();
        }
    })
    return dtd.promise();
}

function initPrincipalS(channelSelectId,company, initCallback){
    var dtd = $.Deferred();
    $.ajax({
        url:config.url +"/recipientUser/getAllPrincipal?company="+company,
        type:"get",
        xhrFields:{withCredentials:true},
        success:function (data) {
            if(data){
                // data.unshift({"name":"-请选择-","code":"","selected":true});
                $("#"+channelSelectId).combobox({
                    "textField":"name",
                    "valueField":"code",
                    "panelHeight":"150",
                    "data":data
                });
                dtd.resolve();
                // 回调函数
                if(typeof initCallback === "function"){
                    if(data.length>=2){
                        $("#"+channelSelectId).combobox('select', data[1]['code']);
                    }
                    initCallback();
                }
            }
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
            dtd.reject();
        }
    });
    return dtd.promise();
}

//复制
function copyText(text) {
    if (text == "") {
        return false;
    }
    var textarea = document.createElement("textarea");
    var currentFocus = document.activeElement;
    document.body.appendChild(textarea);
    textarea.value = text;
    textarea.focus();
    if (textarea.setSelectionRange)
        textarea.setSelectionRange(0, textarea.value.length);
    else
        textarea.select();
    try {
        var flag = document.execCommand("copy");
    } catch(eo){
        var flag = false;
    }
    document.body.removeChild(textarea);
    currentFocus.focus();
    return flag;
}

//获取当月的最后一个礼拜天所在当年的周数
function getWeekNumByMonth(year,month) {
    //下月的第0天即为当月的最后一天，这里不加1是因为date的月从0开始
    let lastDay = new Date(year, month, 0); //本月最后一天
    let day = lastDay.getDay(); //本月最后一天为礼拜几
    // 今天减今年的第一天（xxxx年01月01日）
    const hasTimestamp = lastDay - new Date(year, 0, 1);
    const hasDays = Math.ceil((hasTimestamp - day % 7 * 24 * 60 * 60 * 1000) / (7 * 24 * 60 * 60 * 1000));
    //根据当年的第几天除7向上取整
    return hasDays;
}

//根据周数获取所在周最后一天所在的月份
function getMonthByWeekNum(year,weekNum) {
    var start = new Date(year + '/01/01');
    let day = start.getDay(); //获取本年第一天是礼拜几
    // 所在周数的礼拜日的具体时间=元旦节+第一周剩余的天数+周数对应的天数
    var lastNow = new Date(start.getTime() + (7 - day) * 24 * 60 * 60 * 1000 + (weekNum - 1) * 7 * 24 * 60 * 60 * 1000);
    // console.log(lastNow.toLocaleDateString());
    return lastNow.getMonth() + 1;

}

function bUpdate() {
    var v=$('#username').text();
    alert(v)
    $("#update").window("open");
}function bUpdate() {
    var v=$('#username').text();
    alert(v)
    $("#update").window("open");
}


function initgzCategorySelect(selectId, onchange, callback){
    var dtd = $.Deferred();
    var data = window.parent.userCategoryManageList.slice();
    if(data){
        data.unshift({"name":"","code":""});
        $("#"+selectId).combobox({
            "textField":"name",
            "valueField":"code",
            "panelHeight":150,
            "prompt":"--请选择--",
            "data":data,
            onChange:function(newValue,oldValue){
                if(onchange && typeof onchange === 'function'){
                    var val = $(this).combobox("getText");
                    var textField = $(this).combobox("options").textField;
                    var matchSize = $(this).combobox("getData").filter(function(item){
                        return item[textField]==val;
                    }).length;
                    if(matchSize!=1){
                        return false;
                    }
                    if(newValue=="")return false;
                    onchange.call(this,newValue);
                }
            }
        }).combobox("setValue",data[0]);
        callback && typeof(callback)==='function' && callback();
    }
    dtd.resolve();
    return dtd.promise();
}
function aRecords(features,fName) {
    var data = getFormData(document.getElementById("ff"));
    data.features = features;
    data.fName = fName;
    $.ajax({
        url:config.url + "/accessRecords/data",
        type:"GET",
        data:transfer(data),
        contentType:"application/json;charset=UTF-8",
        dataType:'json',
        xhrFields:{withCredentials:true},
        // beforeSend:function () {
        //     $.messager.progress({
        //         title:"请稍等",
        //         interval:50,
        //         text:"数据加载中..."
        //     });
        // },
        // complete:function () {
        //     $.messager.progress("close");
        // },
        success:function (data) {
            // $.messager.progress("close");
            // if(data){
            //     globalData = data;
            //     $("#datagrid").datagrid("loadData",data);
            //     dtd.resolve();
            // }
        },
        error:function (XMLHttpRequest,textStatus,errorThrown) {

        }
    });
}